package com.demo.springBoot2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.springBoot2.anno.AutoCustomAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.demo.springBoot2.entity.UsersInfo;
import com.demo.springBoot2.entity.dto.UsersInfoLoginDTO;
import com.demo.springBoot2.mapper.UsersInfoMapper;
import com.demo.springBoot2.service.IUsersInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author wuHua·pl
 * @since 2024-03-16
 */
@Slf4j
@Service
public class UsersInfoServiceImpl extends ServiceImpl<UsersInfoMapper, UsersInfo> implements IUsersInfoService {
    @Autowired
    private UsersInfoMapper usersInfoMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public UsersInfo getUserByName(String username) {
        return usersInfoMapper.selectUserByName(username);
    }

    @Override
    public UsersInfoLoginDTO userLogin(UsersInfo usersInfo) {
        UsersInfoLoginDTO userLoginDTO = new UsersInfoLoginDTO();
        if (usersInfo != null) {
            UsersInfo bean = usersInfoMapper.selectUserByName(usersInfo.getUsername());
            // 生成一个盐值（随机20位的字符）
            String salt = bean.getSalt();
            String password = generateSecureHash(usersInfo.getPassword(), salt);
            if (password.equals(bean.getPassword())) {
                BeanUtil.copyProperties(bean, userLoginDTO);
                userLoginDTO.setPhone(DesensitizedUtil.mobilePhone(bean.getPhone()));
                userLoginDTO.setIdCard(DesensitizedUtil.idCardNum(bean.getIdCard(), 6, 4));
                return userLoginDTO;
            }
        }
            return null;
    }

    @Override
    public List<UsersInfoLoginDTO> getUserByPhone(String phone,Integer userId) {
        return usersInfoMapper.selectUserByPhone(phone,userId);
    }

    @Override
    public UsersInfoLoginDTO getUserByUserId(Integer userId) {
        UsersInfoLoginDTO usersInfoLoginDTO = new UsersInfoLoginDTO();
//        String key = "user_"+userId;
//        ValueOperations<String,UsersInfo> operations = redisTemplate.opsForValue();
//        boolean hasKey = redisTemplate.hasKey(key);
//        if (hasKey) {
//            UsersInfo usersInfo = operations.get(key);
//            BeanUtil.copyProperties(usersInfo,usersInfoLoginDTO);
//            System.out.println("从缓存中获取了用户 id = " + key);
//            return usersInfoLoginDTO;
//        }
        UsersInfo usersInfo = usersInfoMapper.selectUserByUserId(userId);
        BeanUtil.copyProperties(usersInfo,usersInfoLoginDTO);
//        System.out.println("从数据库中获取了用户 id = " + key);
//        operations.set(key,usersInfo);
        return usersInfoLoginDTO;
    }

    /**
     * 密码进行加密和加盐
     * */
    public static String generateSecureHash(String password,String salt){
        //得到md5加密对象
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        //（设置盐值）
        md5.setSalt(salt.getBytes());
        //digest 消化 Hex 16进制(对注册密码进行加密)
        String md5Pass = md5.digestHex(password);
        return md5Pass;
    }

    @Override
    public List<UsersInfoLoginDTO> findByPhone(String phone) {
        //通过手机号模糊查询用户然后脱敏转List<DTO>并返回
        //查询条件是模糊查询
        QueryWrapper<UsersInfo> queryWrapper = new QueryWrapper<UsersInfo>()
                .like("phone",phone);
        //查询一个集合
        List<UsersInfo> usersInfos = list(queryWrapper);
        //装备一个list用来保存dto
        ArrayList<UsersInfoLoginDTO> userLoginDTO2s = new ArrayList<>();
        //判断查询数据是否为空
        if(usersInfos!=null){
            //遍历结果
            for(UsersInfo usersInfo:usersInfos){
                //new一个dto
                UsersInfoLoginDTO userLoginDTO = new UsersInfoLoginDTO();
                //entity转dto
                BeanUtil.copyProperties(usersInfo,userLoginDTO);
                //脱敏
                userLoginDTO.setPhone(DesensitizedUtil.mobilePhone(userLoginDTO.getPhone()));
                userLoginDTO.setIdCard(DesensitizedUtil.idCardNum(userLoginDTO.getIdCard(),3,6));
                //dto放入集合
                userLoginDTO2s.add(userLoginDTO);
            }
        }
        //返回
        return userLoginDTO2s;
    }


    @AutoCustomAnnotation(group = "userinfo:")
    @Override
    public UsersInfo selectById(Integer id) {
        return getById(id);
    }

}
